{% extends "mdm/basemdm.html" %}

{% block title %} {{ titulo }} {% endblock %}


{% block contenido %}
     <div id="contenido">
          <div id="izq">
               <div id="promociones">
                    {% for promo in promos  %}
                        <div  id="divpromo_{{ promo.id }}">
                              <h3 id="promo{{ promo.id }}"><a href="#">{{ promo.nombre }}</a></h3>
                         </div>
                    {% endfor %}
               </div>
               <a id="npromo" href="{% url npromo %}" style="width: 99%">Nueva promoci&oacute;n</a>
          </div>
          <div id="der" class="sombra ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
               <div id="tabs">
                    <ul>
                         <li><a href="#tab1">Datos de la promoci&oacute;n</a></li>
                         <li><a href="#tab2">Fotos y planos</a></li>
                    </ul>
                    <div id="tab1">
                        <!--form id="promo"-->
                         <table>
                              <tr>
                                   <td>Nombre de la promoci&oacute;n </td><td>Visibilidad, vigencia</td>
                              </tr>
                              <tr>
                                   <td><input type="text" value="" name="nombre" id="nombre" class="texto"/></td>
                                   <td>
                                        <input type="checkbox" value="True" name="enmenu"  id="enmenu" class="chk"/>Se ve en el men&uacute;
                                        <input type="checkbox" value="True" name="vigente"  id="vigente" class="chk"/>Está vigente
                                   </td>     
                              </tr>
                              <tr>
                                   <td>Descripci&oacute;n</td><td>Direcci&oacute;n, c&oacute;digo postal, localidad</td>
                              </tr>
                                   <td><textarea id="descripcion" name="descripcion"></textarea></td>
                                   <td>
                                        <input type="text" value="" name="direccion"  id="direccion" class="texto"/><br/>
                                        <input type="text" value="" name="cp"  id="cp" class="cp"/>
                                        <input type="text" value="" name="localidad" id="localidad" class="loc"/>                              
                                   </td>
                              </tr>
                              <tr>
                                   <td>Memoria de calidades</td><td>Fecha de fin de encuesta</td>
                              </tr>
                              <tr>
                                   <td rowspan="2"><textarea id="memoria" name="memoria"></textarea></td>
                              </tr>
                              <tr>
                                   <td><input type="text" value=""  name="fecha"  id="fecha" class="vDateField"/></td>
                              </tr>
                              <!--/form-->
                              <tr>
                                   <td class="fina"><button id="guardar1">Guardar</button></td>
                              </tr>
                         </table>
                    </div>
                    <div id="tab2">
                         <div class="demo ui-widget ui-helper-clearfix">
                              <div id="fotosfon" class="ui-widget-content ui-state-default">
                                   <h4 class="ui-widget-header"><span>Fotos de fondo<button id="newf" href="#" rel="F">A&ntilde;adir foto</button></span></h4>
                                   <ul id="Ful" class="gallery ui-helper-reset ui-helper-clearfix"></ul>
                              </div>
                              <div id="fotoscon" class="ui-widget-content ui-state-default">
                                   <h4 class="ui-widget-header"><span>Fotos de contenido<button id="newfp" href="#" rel="FP">A&ntilde;adir foto</button></span></h4>
                                   <ul id="FPul" class="gallery ui-helper-reset ui-helper-clearfix"></ul>
                              </div>
                              <div id="planos" class="ui-widget-content ui-state-default">
                                   <h4 class="ui-widget-header"><span>Planos<button id="newpl" href="#" rel="P">A&ntilde;adir plano</button></span></h4>
                                   <ul id="Pul" class="gallery ui-helper-reset ui-helper-clearfix"></ul>                            
                              </div>
                         </div>
                    </div>                    
               </div>
          </div>
     </div>
     <div id="up_div">
          <div class="upload_div ui-dialog ui-widget ui-widget-content ui-corner-all" title="A&ntilde;adir fotos">
               <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"><span class="ui-dialog-title" id="ui-dialog-title-1">Añadir fotos</span></div>
               <div class="c">
                    <div id="upload_btn"></div>
                    <div id="divStatus">0 archivos subidos</div>
                    <div id="fsUploadProgress" class="fieldset flash"></div>
               </div>
               <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
                    <div class="ui-dialog-buttonset"><button id="cerrarFrm" href="#">Cerrar</button></div>
               </div>
          </div>
     </div>

{% endblock  %}

{% block script %}
     <script>
     var actual = ''
     var tabactual = 0
     var fotosya = false
     var promoya = false
     var dirty = false
     var stop = false
     var swfu
     var params = {'{{session_cookie_name}}': '{{session_key}}', '{{ csrf_token_name }}': '{{ csrf_token }}'}
     $(
          function() {

               $( "#promociones h3" ).click(
                    function( event ) {
                         if ( stop ) {
                              event.stopImmediatePropagation()
                              event.preventDefault()
                              stop = false
                         } else {
                              var adelante = true
                              if (dirty) adelante = confirm('Hay cambios sin guardar. ¿Continuar?')
                              if (adelante) {
                                   params['promo_id'] = $(this).attr('id').replace('promo', '')
                                   if (tabactual == 0) {
                                        fotosya = false
                                        cargaPromo($(this).attr('id'))
                                   } else {
                                        promoya = false
                                        cargaFotos($(this).attr('id'))
                                   }
                              } else {
                                   event.stopImmediatePropagation()
                                   event.preventDefault()
                              }
                         }
                    }
               )

               $( "#promociones" ).accordion(
                    {
                         header: '> div > h3',
                         icons: { 'header': 'ui-icon-triangle-1-e', 'headerSelected': 'ui-icon-circle-triangle-e' }
                    }
               ).sortable(
                    {
                         axis: 'y',
                         handle: 'h3',
                         stop: 
                              function() {
                                   stop = true
                              },
                         update: 
                              function(event, ui) {
                                   reordenapromo()
                              }
                    }
               )
               
               $('#tabs').tabs({
                    selected: 0,
                    select: 
                         function(event, ui) {
                              tabactual = ui.index
                              if (tabactual == 0) {
                                   if (!promoya) cargaPromo(actual)
                              } else {
                                   if (!fotosya) cargaFotos(actual)
                              }
                              
                         }
                    }
               )
               
               $('#guardar1').button().click(
                    function(event, ui) { 
                         guardar()
                         event.stopImmediatePropagation()
                         event.preventDefault()
                    }
               )
               
               $('input').change(
                    function(event, ui){
                         hayCambios()
                    }
               )
               
               tinyMCE.init(
                    {
                    mode : 'exact',
                    elements : 'descripcion, memoria',
                    theme : 'advanced',
                    plugins: 'fullscreen',
                    theme_advanced_buttons1 : 'bold, italic, underline, strikethrough, separator, justifyleft,  justifycenter, justifyright,  justifyfull, separator, fullscreen',
                    theme_advanced_buttons2: '',
                    theme_advanced_buttons3: '',
                    theme_advanced_buttons4: '',
                    theme_advanced_toolbar_location : 'top',
                    theme_advanced_toolbar_align : 'left',
                    width: '100%',
                    onchange_callback : 'hayCambios'
                    }
               )
               
               $('#newf, #newfp, #newpl').button(
                    {
                         icons: {
                              primary: "ui-icon-plus"
                              },
                         text: false
                    }
               ).click(
                    function(){
                         $('#up_div').fadeIn()
                         params['tipo_media'] = $(this).attr('rel')
                    }
               )
               
               $( 'ul.gallery > li' ).live(
                    'click',
                    function( event ) {
                         var $item = $( this ),
                              $target = $( event.target )

                         if ( $target.is( 'a.ui-icon-trash' ) ) {
                              deleteImage( $target )
                         } else if ( $target.is( 'a.ui-icon-zoomin' ) ) {
                              viewLargerImage( $target )
                         }
                         return false
                    }
               )
               
               $( 'h5.titulofoto' ).live(
                    'dblclick',
                    function(event) {
                         cambiaTitulo($(event.target))                         
                    }
               )
               
               $('#Ful, #FPul, #Pul').sortable(
                    {
                         tolerance: 'pointer',
                         update: 
                              function(event, ui) {
                                   reordenar(ui.item)
                              }
                    }
               )
               $('#Ful, #FPul, #Pul').disableSelection()
              
               var settings = 
                    {
                         debug: false,
                         upload_url: '{% url mdm.views.subida %}',
                         flash_url: '{{ MEDIA_URL }}mdm/js/swfupload.swf',
                         button_placeholder_id: 'upload_btn',
                         button_width: '96',
                         button_height: '29',
                         button_image_url : '{{ MEDIA_URL }}mdm/js/examina.png',
                         file_types_description:  'Imágenes', 
                         file_types: '*.png;*.jpg;*.gif',
                         file_size_limit : '3 MB', 
                         file_upload_limit : 100,
                         file_queue_limit : 0,
                         custom_settings : {
                              progressTarget : "fsUploadProgress",
                              //~ cancelButtonId : "btnCancel"
                         },
                         button_cursor: SWFUpload.CURSOR.HAND,
                         //~ file_dialog_complete_handler: function() { this.startUpload() },
                         //~ upload_complete_handler: function() { this.startUpload()},
                         //~ post_params:  {'{{session_cookie_name}}': '{{session_key}}', 'csrfmiddlewaretoken': '{{ csrf_token }}', '{{ csrf_token_name }}': '{{ csrf_token }}'},
                          // The event handler functions are defined in handlers.js
                         file_queued_handler : fileQueued,
                         file_queue_error_handler : fileQueueError,
                         file_dialog_complete_handler : fileDialogComplete,
                         upload_start_handler : uploadStart,
                         upload_progress_handler : uploadProgress,
                         upload_error_handler : uploadError,
                         upload_success_handler : uploadSuccess,
                         upload_complete_handler : uploadComplete,
                         queue_complete_handler : queueComplete // Queue plugin event 
                    }
                    
               swfu = new SWFUpload(settings)               
               
               $('#npromo').button()
               
               $('#cerrarFrm').button().click(
                    function() {
                         if($('#divStatus').text() != '0 archivos subidos') {
                              cargaFotos(actual)
                              $('#divStatus').text('0 archivos subidos')
                         }
                         $('#up_div').fadeOut()
                    }
               )
               
               params['promo_id'] = $('#promociones div h3').attr('id').replace('promo', '')
                $(document).ajaxStop($.unblockUI)
               setTimeout("cargaPromo($('#promociones div h3').attr('id'))", 500)
          }
     )
     
     function cargaPromo(id){
          espera()
          $.post(
               '{% url datos %}' + '/' + id.replace('promo', ''), 
               '',
               function(data){
                   rellenar(data)
               },
               'json'
          )
          if (actual) $('#' + actual).parent().removeClass('sombra')
          $('#' + id).parent().addClass('sombra')
          actual = id
          dirty = false
          promoya = true
          if ($('#guardar1').is(':visible')) $('#guardar1').fadeOut()
          //~ $('#promociones div h3').attr('id').replace('promo', '')
     }
          
     function cargaFotos(id){
          espera()
          $.post(
               '{% url fotos %}' + '/' + id.replace('promo', ''), 
               '',
               function(data){
                   fotos(data)
               },
               'json'
          )
          if (actual) $('#' + actual).parent().removeClass('sombra')
          $('#' + id).parent().addClass('sombra')
          actual = id
          dirty = false
          fotosya = true
          if ($('#guardar1').is(':visible')) $('#guardar1').fadeOut()
          //~ if ($('#guardar2').is(':visible')) $('#guardar2').fadeOut()
     }
     
     function rellenar(dat) {
          for (x in dat) {
               ctrl = $('#' + x)
               if (ctrl.is(':checkbox')) {
                    ctrl.attr('checked', dat[x])
               } else {
                    ctrl.val(dat[x])
               }
          }
          var ds = tinyMCE.get('descripcion')
          if (ds) ds.setContent(dat.descripcion)
          var mem = tinyMCE.get('memoria')
          if (mem) mem.setContent(dat.memoria)
     }
     
     function fotos(datos) {
          $('#Ful, #FPul, #Pul').empty()
          var dat = sortObject(datos)
          for (x in dat) {
               cur = dat[x]
               im =  '<li class="bordea ui-widget-content ui-corner-tr" id="img_' + cur.tipo + '_' + cur.id + '"><h5 class="ui-widget-header titulofoto">' + cur.ds + '</h5><div class="imgcont"><img alt="' + cur.ds + '" src="'
               if (cur.thumb != '') {
                    im += cur.thumb
               } else {
                    im += cur.foto
               }
               im += '" width="100"/></div><a href="' + cur.foto + '" title="Ampliar" class="ui-icon ui-icon-zoomin">Ampliar</a>'
               im += '<span>' + cur.size[0] + 'x' + cur.size[1] + '</span><a href="#" title="Borrar" class="ui-icon ui-icon-trash" rel="' + cur.id + '">Borrar</a></li>'
               $('#' + cur.tipo + 'ul').append(im)               
          }
     }
     
     function hayCambios($target){
          dirty = true
          if (!$('#guardar1').is(':visible')) $('#guardar1').fadeIn()
     }
     
     function guardar() {
          var fr = {}
          $('input, textarea').each(
               function(){
                    if ($(this).attr('name') == 'fecha') {
                         trozos = $(this).val().split('/')
                         fr[$(this).attr('name')] = trozos[2] +'-' + trozos[1] +'-' +trozos[0]
                    } else if ($(this).is(':checkbox')) {
                         fr[$(this).attr('name')] = ($(this).is(':checked') ? '1' : '')
                    } else if ($(this).is('textarea')){
                         fr[$(this).attr('name')] = tinyMCE.get($(this).attr('name')).getContent()                         
                    } else {
                         fr[$(this).attr('name')] = $(this).val()
                    }
               }
          )
          $.post(
               '{% url actualizapromo %}', 
               {'promo_id': actual.replace('promo', ''), 'campos': JSON.stringify(fr) }
          )
          $.post(
               '{% url arreglamnu %}'
          )          
          $('#guardar1').fadeOut()
          dirty = false          
         $('#' + actual + ' a').text($('#nombre').val())
     }
     
       
     function espera() {
          $.blockUI({message: '<h3><img src="{{MEDIA_URL}}img/superbgloading.gif" style="vertical-align: middle; margin: 5px">Espere, por favor...</h3>'})
     }
     
     // image preview function, demonstrating the ui.dialog used as a modal window
     function viewLargerImage( $link ) {
          var src = $link.attr( 'href' ),
          title = $link.siblings( 'img' ).attr( 'alt' ),
          $modal = $( 'img.chopo[src$="' + src + '"]' )
          if ( $modal.length) {
               $modal.dialog( 'open' )
          } else {
               var img = $( '<img class="chopo" alt="' + title + '" style="display: none padding: 8px" />' )
                    .attr( 'src', src ).appendTo( 'body' )
               var ancho = parseInt($link.siblings('span').text().split('x')[0]) + 35
               setTimeout(function() {
                    img.dialog({
                         title: title,
                         modal: true,
                         minWidth: ancho,
                         positon: 'top',               
                         resizable: false
                    })
               }, 100 )
          }
     }

     function deleteImage($cual) {
          if (confirm('¿Borrar la imagen?')) {
               $.post(
                    '{% url borrafoto %}', 
                    {'media_id':  $cual.attr('rel')}
               )
               cargaFotos(actual)
          }         
     }
     
     function reordenar(ui) {
          espera()
          var nms = ui.attr('id').split('_')
          var arr = $('#' + nms[1] + 'ul').sortable('toArray')
          var n = 0
          for (x in arr) {
              $.post(
                    '{% url ordenafoto %}', 
                    {'media_id': arr[x].split('_')[2], 'orden': n}
               )
               n++               
          }
     }
         
     function reordenapromo() {
          espera()
          var arr = $('#promociones').sortable('toArray')
          var n = 0
          for (x in arr) {
              $.post(
                    '{% url ordenapromo %}', 
                    {'promo_id': arr[x].replace('divpromo_', ''), 'orden': n}
               )
               n++               
          }
          $.post(
               '{% url arreglamnu %}'
          )       
     }
     
     function cambiaTitulo($target) {
          titulo_a = ($target.text() == 'Sin descripción' ? '' : $target.text())
          titulo_m = prompt('Escriba la descripción de la imagen', titulo_a)
          if (titulo_a != titulo_m) {
               $.post(
                    '{% url cambiatitulo %}', 
                    {'media_id': $target.parent('li').attr('id').split('_')[2], 'ds': titulo_m}
               )
               $target.text((titulo_m == '' ? 'Sin descripción' : titulo_m))
          }
     }
     
     function sortObject(o) {
         var sorted = {},
         key, a = [];

         for (key in o) {
             if (o.hasOwnProperty(key)) {
                     a.push(key);
             }
         }

         a.sort();

         for (key = 0; key < a.length; key++) {
             sorted[a[key]] = o[a[key]];
         }
         return sorted;
     }

     
     </script>
{% endblock  %}
